package zw.netty.server.Netty.Handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import zw.netty.server.Netty.NettyServer;
import zw.netty.server.pojo.Device;
import zw.netty.server.web.WsController;

import java.nio.charset.Charset;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-09-11 10:42
 */
public class HexHandler extends ChannelInboundHandlerAdapter {

    private SimpMessagingTemplate template;

    public HexHandler(SimpMessagingTemplate template){
        this.template=template;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf data=(ByteBuf)msg;
        String str=data.toString(Charset.defaultCharset());
        try{
            if(str.indexOf("body")!=-1||str.indexOf("6050")!=-1||str.indexOf("50960")!=-1){
                System.out.println(str);
                Device device=  JSON.parseObject(str,Device.class);
                 if(device.getName().equals("50960")) {
                    template.convertAndSend("/topic/mpu6050",str);
                }
            }else if(str.indexOf("$GNRMC")!=-1){
                System.out.println(str);
                template.convertAndSend("/topic/gps",str);
            }else {
                byte[] receiveMsgBytes = new byte[data.readableBytes()];
                data.readBytes(receiveMsgBytes);
                Device device=new Device();
                System.out.println(HandUtil.bytesToHexString(receiveMsgBytes));
                if((receiveMsgBytes[0] & 0xFF)==0x78){
                    device.setName("shouhuan");
                    device.setState(Integer.parseInt(Integer.toHexString(receiveMsgBytes[3] & 0xFF)));
                    device.setBody(HandUtil.DateDecodeHande(receiveMsgBytes,ctx));
                    if(device.getState().intValue()==17||device.getState().intValue()==69||device.getState().intValue()==10){
                        JSONObject json=JSON.parseObject(JSON.parseObject(device.getBody()).getString("gps"));
                        device.setLocation(json.getString("locations"));
                    }
                    //device.setLocation(json.getJSONArray("data"));
                    //System.out.println(HandUtil.bytesToHexString(receiveMsgBytes));
                    System.out.println(device.getBody());
                    template.convertAndSend("/topic/shouhuan",JSON.toJSONString(device));
                }else if((receiveMsgBytes[0] & 0xFF)==0x95){
                    device.setName("ODB");
                    device.setBody(HandUtil.DateDecode(receiveMsgBytes));
                    template.convertAndSend("/topic/odb",JSON.toJSONString(device));
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(msg);
        }

    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有设备接入："+ctx.channel().id().asShortText());
        NettyServer.channelMap.put(ctx.channel().id().asShortText(),ctx.channel());
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端："+ctx.channel()+"断开连接");
        NettyServer.channelMap.forEach((key,obj)->{
            if(obj.id().asShortText().equals(ctx.channel().id().asShortText())){
                obj.writeAndFlush(WsController.count+"");
                NettyServer.channelMap.remove(ctx.channel().id().asShortText());
            }
        });
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }

    public static void main(String[] args) {
            //78 78 12 10 12 09 0d 06 1f 0f 96 03 3e 07 57 0c e7 6a fb 00 34 4f 0d 0a
    }
}
